package com.af.soldiers.job;

import com.af.soldiers.util.JsonHandler;
import com.alibaba.fastjson.JSONArray;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.sql.*;
import java.util.Properties;
import java.util.Set;

@Component
public class RunSql {

    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;

    @Autowired
    private JsonHandler jsonHandler;

    private static final Logger logger = LoggerFactory.getLogger(RunSql.class);

    public JSONArray select(String sql) throws SQLException {
        logger.debug("执行select语句:"+sql);
        Statement statement;
        Connection connection = sqlSessionTemplate.getSqlSessionFactory().openSession().getConnection();
        statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(sql);
        JSONArray handle = jsonHandler.handle(resultSet);
        logger.debug("select Over");
        statement.close();
        connection.close();
        return handle;
    }

    public Integer update(String sql) throws SQLException {
        logger.debug("执行update语句:"+sql);
        Statement statement;
        Connection connection = sqlSessionTemplate.getSqlSessionFactory().openSession().getConnection();
        statement = connection.createStatement();
        Integer i = statement.executeUpdate(sql);
        logger.debug("update Over");
        statement.close();
        connection.close();
        return i;
    }

    public String call(String name) throws SQLException {
        logger.debug("执行call名称:"+name);
        String sql = "{call  "+name+"}";
        Connection connection = sqlSessionTemplate.getSqlSessionFactory().openSession().getConnection();
        CallableStatement callableStatement = connection.prepareCall(sql);
        ResultSet resultSet = callableStatement.executeQuery();
        resultSet.next();
        String string = resultSet.getString(1);
        callableStatement.close();
        connection.close();
        return string;
    }

    public void execute(String sql) throws SQLException {
        logger.debug("执行execute的SQL:"+sql);
        Connection connection = sqlSessionTemplate.getSqlSessionFactory().openSession().getConnection();
        Statement statement =  connection.createStatement();
        statement.execute(sql);
        statement.close();
        connection.close();
    }

}
